package com.ailot.cloud.base.security.config;

import com.ailot.cloud.base.common.constants.SecurityConstant;
import com.ailot.cloud.base.security.handler.JwtAccessDeniedHandler;
import com.ailot.cloud.base.security.handler.JwtAuthenticationEntryPoint;
import com.ailot.cloud.base.security.properties.PermitAllUrlProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@EnableWebSecurity
@EnableConfigurationProperties({PermitAllUrlProperties.class})
public class ResourceSecurityConfigurer {


    //
    private PermitAllUrlProperties permitAllUrlProperties;
    private List<AntPathRequestMatcher> antPathRequestMatcherList;

    public ResourceSecurityConfigurer(PermitAllUrlProperties permitAllUrlProperties) {
        this.permitAllUrlProperties = permitAllUrlProperties;
    }

    @PostConstruct
    public void antPathMatcherList() {
        this.antPathRequestMatcherList = Optional.ofNullable(permitAllUrlProperties.getUrls()).orElse(new ArrayList<>()).stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
    }


    /**
     * 内部请求的标记
     * 内部请求 必须含有 内部请求的标头。
     * 并且没有 token 信息携带
     * 如果携带token信息 应该是优先token 处理认证
     */
    private static final RequestMatcher INTERNAL_REQUEST = (req) ->
            // 包含内部请求标头的
            req.getHeader(SecurityConstant.FROM) != null && req.getHeader(SecurityConstant.FROM).equalsIgnoreCase(SecurityConstant.FROM_IN)
                    // 并且不包含token信息
                    && req.getHeader(HttpHeaders.AUTHORIZATION) == null;

    private final RequestMatcher PERMIT_ALL_REQUEST = (req) ->
            // 并且不包含token信息
            req.getHeader(HttpHeaders.AUTHORIZATION) == null &&
                    // 符合任意规则
                    this.antPathRequestMatcherList.stream().anyMatch(m -> m.matches(req));

    /**
     * 资源服务权限配置
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return
                http
                        .authorizeRequests()
                        // 白名单不拦截
                        .requestMatchers(PERMIT_ALL_REQUEST)
                        .permitAll()
                        //内部请求不拦截
                        .requestMatchers(INTERNAL_REQUEST)
                        .permitAll()
                        .anyRequest().authenticated()
                        .and()
                        .formLogin(form -> form.disable())
                        .cors(cors -> cors.disable())
                        .csrf(csrf -> csrf.disable())
                        .oauth2ResourceServer(oauth2ResourceServer -> oauth2ResourceServer
                                .jwt()
                                .jwtAuthenticationConverter(c -> {
                                    JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
                                    jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(SecurityConstant.AUTHORITIES);
                                    jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
                                    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
                                    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
                                    return jwtAuthenticationConverter.convert(c);
                                })
                        )
                        //禁用session，JWT校验不需要session
                        .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                        .exceptionHandling(exception -> exception
                                //未授权异常
                                .accessDeniedHandler(new JwtAccessDeniedHandler())
                                .authenticationEntryPoint(new JwtAuthenticationEntryPoint())
                        ).build();


    }


    /**
     * 账号密码的加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    }
}
